// store/permission.ts (Pinia/Vuex状态管理)
import { defineStore } from 'pinia'
import { RouteLocationNormalized } from 'vue-router'
import type { PersistenceOptions } from 'pinia-plugin-persistedstate' // 修改类型导入


// 新增 TagView 类型声明
export interface TagView extends Partial<RouteLocationNormalized> {
    title?: string
    affix?: boolean
}


export const usePermissionStore = defineStore('permission', {
    state: () => ({
        visitedViews: [] as TagView[],
        cachedViews: [] as string[]
    }),
    // 添加类型断言（关键修改）
    persist: {
        key: 'tags-view',
        paths: ['visitedViews'],
        storage: sessionStorage
    } as PersistenceOptions, // 类型断言

    actions: {
        // 添加访问记录
        addVisitedView(view: TagView) {
            // 排除重复和404页面
            if (view.path?.includes('404')) return
            const index = this.visitedViews.findIndex(v => v.path === view.path)
            if (index >= 0) {
                this.visitedViews[index] = { ...view }
            } else {
                this.visitedViews.push({ ...view })
            }
        },
        // 删除标签
        delVisitedView(path: string) {
            this.visitedViews = this.visitedViews.filter(v => v.path !== path)
        },
        // 清空标签
        clearVisitedViews() {
            this.visitedViews = ['首页', 'true']
        },
        // 保留固定标签
        clearAllExceptAffix() {
            this.visitedViews = this.visitedViews.filter(v => v.meta?.affix)
        }
    }
})
